package com.apts.controller;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apts.jfinalbase.BaseController;
import com.apts.pojo.ErrorPojo;
import com.apts.pojo.NomalPojo;
import com.apts.util.FileToZipUtil;
import com.apts.util.FileUtil;
import com.apts.util.QrCodeUtil;
import com.jfinal.core.JFinal;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class QRcodeController extends BaseController {

	// 二维码生成
	public void QRcodeGenerate() throws UnknownHostException {
		// 公用数据
		String codecreatetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());// 当前时间
		String codePath = JFinal.me().getServletContext().getRealPath("/") + File.separator + "code" + File.separator;// 二维码生成路径
		int currentPiNo = 0;// 初始批号数字
		String realcodePrefix = String.valueOf(new Date().getTime()); // 二维码实体编号前缀

		// 前台参数
		String regcode = this.getPara("regcode");// 企业注册号
		String typecode = this.getPara("typecode");// 品种类型编号
		String fromarea = this.getPara("fromarea");// 生产地
		String startdate = this.getPara("startdate");// 生产日期
		String expdate = this.getPara("expdate");// 保质期
		String codeOvertime = this.getPara("codeOvertime");// 二维码失效时间
		String codeNum = this.getPara("codeNum");// 二维码生成数目

		int count = 0;
		try {
			count = Integer.parseInt(codeNum);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 批号生成
		List<Record> PiNoList = Db.find("SELECT DISTINCT codePiNO FROM tb_real_roots ORDER BY codePiNO DESC");
		if (PiNoList.size() > 0) {
			currentPiNo = PiNoList.get(0).getInt("codePiNO") + 1;
		} else {
			currentPiNo = 1;
		}

		// 拼接sql语句（批插入）
		String sql = " INSERT INTO tb_real_roots ( realcode,regcode,typecode,fromarea,startdate,expdate,codePiNO,codecreatetime,codeOvertime ) VALUES ";
		for (int i = 1; i <= count; i++) {
			String realcode = realcodePrefix + "-" + i;
			int codePiNO = currentPiNo;
			if (i != 1) {
				sql = sql + " , ";
			}
			sql = sql + " ( '" + realcode + "','" + regcode + "','" + typecode + "','" + fromarea + "','" + startdate
					+ "','" + expdate + "','" + codePiNO + "','" + codecreatetime + "','" + codeOvertime + "' ) ";
		}
		Db.update(sql);

		File dir = new File(codePath + currentPiNo);
		if (dir.exists()) {
			FileUtil.DeleteFolder(codePath + currentPiNo);
		}
		dir.mkdir(); // 只能创建单个目录

		// 获取本机IP
		String ip = InetAddress.getLocalHost().getHostAddress();
		for (int i = 1; i <= count; i++) {
			String address = "http://" + ip + "/#!/wap/" + currentPiNo + "-" + realcodePrefix + "-" + i;
			System.out.println(address);
			QrCodeUtil.createQRCode(address, codePath + currentPiNo + File.separator + i + ".jpg", null);
		}

		// 打包二维码，并删除存储二维码的文件夹
		if (FileToZipUtil.fileToZip(codePath + currentPiNo, codePath, currentPiNo + "")) {
			// FileUtil.DeleteFolder(codePath + currentPiNo);
		}

		this.renderJson(new NomalPojo());

	}

	// // 二维码扫描
	// public void QRcodeScan() {
	// String id = this.getPara("id");// 二维码记录的id
	// BaseJsonPojo json = QRcodeServise.Servise.QRcodeScan(id);
	// this.renderJson(json);
	// }

	// 二维码扫描
	public void QRcodeScan2() {
		String code = this.getPara("code");// 二维码记录的id
		String realcode = code.substring(code.indexOf("-") + 1, code.length());

		List<Record> realCodes = Db.find(" select * from tb_real_roots where realcode = ?  ", realcode);

		if (realCodes.size() < 1) {
			this.renderJson(new ErrorPojo("二维码不存在！！！"));
			return;
		}
		Date activeStatus = realCodes.get(0).get("codeActivetime");
		if (activeStatus == null) {
			this.renderJson(new ErrorPojo("二维码未激活！！！"));
			return;
		}

		String e_id = realCodes.get(0).getStr("regcode");
		String t_id = realCodes.get(0).getStr("typecode");
		List<Record> e_name = Db.find(" select * from tb_enterprise where regcode = ?  ", e_id);
		List<Record> type_foods = Db.find(" select * from tb_product_type where typecode = ?  ", t_id);

		Integer scanfTimes = realCodes.get(0).getInt("codescanftimes");
		if (scanfTimes == null) {
			scanfTimes = 0;
		}
		// 更新二维码扫描次数
		++scanfTimes;
		Db.update(" update  tb_real_roots set codescanftimes = ? where realcode =  ? ", scanfTimes, realcode);
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", type_foods.get(0).getStr("typename")); // 品种名
		map.put("times", scanfTimes); // 扫描次数
		map.put("company", e_name.get(0).getStr("epname")); // 生产商
		map.put("address", realCodes.get(0).getStr("fromarea")); // 生产地址
		map.put("startTime", realCodes.get(0).get("codecreatetime")); // 生产时间
		map.put("usableTime", realCodes.get(0).getStr("expdate")); // 保质期
		map.put("info", type_foods.get(0).getStr("typeinfo")); // 品种简介
		map.put("profileimg", type_foods.get(0).getStr("profileimg")); // 品种图

		this.renderJson(new NomalPojo(map));
	}

	// 获取二维码生成历史
	public void CreateHistory() {
		// 获取公司注册号
		String sql = " SELECT codePiNO , tb_enterprise.epname , tb_product_type.typename , codecreatetime , COUNT( codePiNO ) AS codeNum ";
		sql = sql + " FROM tb_real_roots ";
		sql = sql + " INNER JOIN tb_enterprise ON tb_real_roots.regcode = tb_enterprise.regcode ";
		sql = sql + " INNER JOIN tb_product_type ON tb_real_roots.typecode = tb_product_type.typecode ";
		sql = sql + " GROUP BY codePiNO order by codecreatetime desc ";
		List<Record> list = Db.find(sql);

		List<Map<String, Object>> ResultSet = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>(0);
			Record obj = list.get(i);
			map.put("codePiNO", obj.get("codePiNO"));
			map.put("epname", obj.get("epname"));
			map.put("typename", obj.get("typename"));
			map.put("codecreatetime", obj.get("codecreatetime"));
			map.put("codeNum", obj.get("codeNum"));
			ResultSet.add(map);
		}
		Map<String, Object> result = new HashMap<String, Object>(0);
		result.put("list", ResultSet);
		this.renderJson(new NomalPojo(result));
	}

	// 下载文件
	public void DownloadCodeZipFile() {
		String codePiNO = this.getPara("codePiNO");
		String codeZipFileSrc = JFinal.me().getServletContext().getRealPath("/") + File.separator + "code"
				+ File.separator + codePiNO + ".zip";
		File file = new File(codeZipFileSrc);
		if (file.exists()) {
			this.renderFile(file);
			return;
		}
		this.renderJson(new ErrorPojo("文件不存在"));
	}

	/**
	 * 二维码管理查询
	 */
	public void CodeManageList2() {

		String sql = " SELECT  tr.`codePiNO`, te.`epname`, tp.`typename` , tr.`codecreatetime` ,  COUNT( tr.`codePiNO` ) AS codeNum , tr2.`activeNum` ";
		sql = sql + " FROM tb_real_roots tr , tb_enterprise te , tb_product_type tp ,  ";
		sql = sql + " ( ";
		sql = sql + " SELECT tmp.`codePiNO` AS pino , COUNT( tmp.`codeActivetime` ) AS activeNum ";
		sql = sql + " FROM tb_real_roots tmp  ";
		sql = sql + " GROUP BY tmp.`codePiNO` ";
		sql = sql + " ) tr2 ";
		sql = sql
				+ " WHERE te.regcode = tr.`regcode` AND tp.`typecode` = tr.`typecode` AND tr.`codePiNO` = tr2.`pino` ";
		sql = sql + " GROUP BY tr.`codePiNO` ";
		sql = sql + " ORDER BY tr.`codecreatetime` desc ";

		List<Record> list = Db.find(sql);

		List<Map<String, Object>> ResultSet = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>(0);
			Record obj = list.get(i);
			map.put("codePiNO", obj.get("codePiNO"));
			map.put("epname", obj.get("epname"));
			map.put("typename", obj.get("typename"));
			map.put("codecreatetime", obj.get("codecreatetime"));
			map.put("codeNum", obj.get("codeNum"));
			map.put("activeNum", obj.get("activeNum"));
			ResultSet.add(map);
		}
		Map<String, Object> result = new HashMap<String, Object>(0);
		result.put("list", ResultSet);
		this.renderJson(new NomalPojo(result));

	}

	// 二维码搜索查询
	public void CodeManageList() {

		String choose = this.getPara("choose");
		String whereStr = " ";
		// choose == 0 时搜索全部
		// 批号查询
		if (choose.equals("1")) {
			String pino = this.getPara("codePiNO");
			try {
				Integer.parseInt(pino);
			} catch (Exception e) {
				this.renderJson(new ErrorPojo("批号搜索请输入数字"));
				return;
			}
			whereStr = " and tr.`codePiNO` = " + pino + "  ";
		}
		// 公司查询
		if (choose.equals("2")) {
			String epname = this.getPara("epName");
			whereStr = " and te.`epname` LIKE '%" + epname + "%' ";
		}
		// 品种查询
		if (choose.equals("3")) {
			String typeName = this.getPara("typeName");
			whereStr = " and  tp.`typename` LIKE '%" + typeName + "%' ";
		}

		String sql = " SELECT  tr.`codePiNO`, te.`epname`, tp.`typename` , tr.`codecreatetime` ,  COUNT( tr.`codePiNO` ) AS codeNum , tr2.`activeNum` ";
		sql = sql + " FROM tb_real_roots tr , tb_enterprise te , tb_product_type tp ,  ";
		sql = sql + " ( ";
		sql = sql + " SELECT tmp.`codePiNO` AS pino , COUNT( tmp.`codeActivetime` ) AS activeNum ";
		sql = sql + " FROM tb_real_roots tmp  ";
		sql = sql + " GROUP BY tmp.`codePiNO` ";
		sql = sql + " ) tr2 ";
		sql = sql + " WHERE te.regcode = tr.`regcode` AND tp.`typecode` = tr.`typecode` AND tr.`codePiNO` = tr2.`pino` "
				+ whereStr;
		sql = sql + " GROUP BY tr.`codePiNO` ";
		sql = sql + " ORDER BY tr.`codecreatetime` desc ";

		List<Record> list = Db.find(sql);

		List<Map<String, Object>> ResultSet = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < list.size(); i++) {
			Map<String, Object> map = new HashMap<String, Object>(0);
			Record obj = list.get(i);
			map.put("codePiNO", obj.get("codePiNO"));
			map.put("epname", obj.get("epname"));
			map.put("typename", obj.get("typename"));
			map.put("codecreatetime", obj.get("codecreatetime"));
			map.put("codeNum", obj.get("codeNum"));
			map.put("activeNum", obj.get("activeNum"));
			ResultSet.add(map);
		}
		Map<String, Object> result = new HashMap<String, Object>(0);
		result.put("list", ResultSet);
		this.renderJson(new NomalPojo(result));
	}

	// 二维码实体列表（按批号查找）
	public void RealCodeList() {
		String pino = this.getPara("pino");
		String sql = " SELECT tr.`realcode`, tr.`codePiNO`, te.`epname`, tp.`typename`, tr.`codecreatetime`, tr.`codeActivetime`, tr.`codescanftimes`, tr.`codeOvertime` ";
		sql = sql + " FROM tb_real_roots tr ";
		sql = sql + " INNER JOIN tb_enterprise te ON tr.`regcode` = te.`regcode` ";
		sql = sql + " INNER JOIN tb_product_type tp ON tr.`typecode` = tp.`typecode` ";
		sql = sql + " WHERE tr.`codePiNO` = ? ";
		try {
			int args = Integer.parseInt(pino);
			List<Record> list = Db.find(sql, args);
			List<Map<String, Object>> ResultSet = new ArrayList<Map<String, Object>>();
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> map = new HashMap<String, Object>(0);
				Record obj = list.get(i);
				String realcode = obj.get("realcode");
				realcode = realcode.substring(realcode.indexOf('-') + 1, realcode.length());
				map.put("realcode", realcode);
				map.put("codePiNO", obj.get("codePiNO"));
				map.put("epname", obj.get("epname"));
				map.put("typename", obj.get("typename"));
				map.put("codecreatetime", obj.get("codecreatetime"));
				map.put("codeActivetime", obj.get("codeActivetime"));
				map.put("codescanftimes", obj.get("codescanftimes"));
				map.put("codeOvertime", obj.get("codeOvertime"));
				ResultSet.add(map);
			}
			Map<String, Object> result = new HashMap<String, Object>(0);
			
			String sql2 = "  SELECT COUNT( * ) AS acCount FROM tb_real_roots WHERE codePiNO = ? AND codeActivetime IS NOT NULL  ";
			List<Record> acCountList = Db.find(sql2, pino);
			result.put("list", ResultSet);
			result.put("acCount", acCountList.get(0).get("acCount"));
			this.renderJson(new NomalPojo(result));
		} catch (Exception e) {
			this.renderJson(new ErrorPojo("请输入批号查询"));
		}
	}

	// 二维码激活
	public void QRcodeActive() {
		String choose = this.getPara("choose");
		String pino = this.getPara("pino");
		String sql = "  ";
		// 全部激活
		if (choose.equals("1")) {
			sql = " UPDATE `tb_real_roots` SET codeActivetime = now() WHERE codeActivetime IS NULL  AND codePiNO = "
					+ pino + "  ";
		}

		if (choose.equals("2")) {
			String acCount = this.getPara("acCount"); // 激活数量
			int acCountInt = 0;
			try {
				acCountInt = Integer.parseInt(acCount);
			} catch (Exception e) {
				this.renderJson(new ErrorPojo("输入有误"));
			}

			sql = " UPDATE `tb_real_roots` SET codeActivetime = now() WHERE codeActivetime IS NULL  AND codePiNO = "
					+ pino + " ORDER BY id ASC LIMIT " + acCountInt + " ";
		}
		Db.update(sql);

		this.renderJson(new NomalPojo());
	}

}
